package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.login

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.hitPointCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.login.subview.IKeyboardCameroonNumberListener
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.subview.HotlineCameroonDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityCameroonLoginOtpBinding
import java.util.Timer
import java.util.TimerTask

class LoginCameroonOtpActivity : AppCompatActivity() {

    private lateinit var loginViewModel: LoginCameroonViewModel
    private lateinit var binding: ActivityCameroonLoginOtpBinding
    private var timer = Timer()

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        loginViewModel = ViewModelProvider(this)[LoginCameroonViewModel::class.java]

        // 关联布局
        binding = ActivityCameroonLoginOtpBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val hotline = binding.hotline
        val phone = binding.phone
        val keyboard = binding.keyboard
        val loading = binding.loading

        // 保存回传值
        val mobile = intent.getStringExtra("phone") ?: ""
        loginViewModel.phone = mobile
        phone.text =
            "Un code de vérification à 4 chiffres a été envoyé sur votre téléphone mobile $mobile"

        val directLoginFlag = intent.getStringExtra("directLoginFlag") ?: ""
        loginViewModel.directLoginFlag = directLoginFlag

        if (mobile.isBlank()) {
            finish()
            return
        }

        // 页面loading状态接口监听
        loginViewModel.loadingResult.observe(this@LoginCameroonOtpActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 输入监听
        loginViewModel.codeInputState.observe(this@LoginCameroonOtpActivity, Observer {
            val codes = it.codes ?: return@Observer
            binding.code1.text = codes[0]
            binding.code2.text = codes[1]
            binding.code3.text = codes[2]
            binding.code4.text = codes[3]

            if (it.done == true) {
                loading.visibility = View.VISIBLE
                loginViewModel.login()
            }
        })

        // 登录接口监听
        loginViewModel.loginResult.observe(this@LoginCameroonOtpActivity, Observer {
            val loginResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (loginResult.error != null) {
                // TODO: 失败
                showMessage(loginResult.error)
            }
            if (loginResult.success != null) {
                // TODO: 成功
                loginViewModel.mainProcess()
            }
        })

        // 验证码接口监听
        loginViewModel.otpResult.observe(this@LoginCameroonOtpActivity, Observer {
            val otpResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (otpResult.error != null) {
                // TODO: 失败
                showMessage(otpResult.error)
            }

            if (otpResult.directFlag == true) {
                // TODO: 输入otp
                loginViewModel.login()
            }
            if (otpResult.success != null) {
                // TODO: 输入otp
                startCodeTimer()
            }
        })

        // 流程接口监听
        loginViewModel.mainProcessResult.observe(this@LoginCameroonOtpActivity, Observer {
            val mainProcessResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (mainProcessResult.error != null) {
                showMessage(mainProcessResult.error)
            }

            if (mainProcessResult.success != null) {
                loginViewModel.nextRouter(mainProcessResult.success)
            }
        })

        // 页面需要跳转监听
        loginViewModel.nextRouterResult.observe(this@LoginCameroonOtpActivity, Observer {
            val nextRouterResult = it ?: return@Observer

            loading.visibility = View.GONE
            startNextActivity(nextRouterResult.nextPage)
        })

        // 键盘输入监听
        keyboard.setListener(object : IKeyboardCameroonNumberListener {
            override fun onClick(tid: String) {
                if (tid == "-1") {
                    // 删除
                    loginViewModel.loginOtpDataChanged(true, "")

                } else if (tid == "-2") {
                    // 收起键盘
                    binding.keyboard.visibility = View.GONE

                } else {
                    // 变动
                    loginViewModel.loginOtpDataChanged(false, tid)
                }
            }
        })

        // 点击获取otp
        binding.resend.setOnClickListener {
            val resendStr = binding.resend.text.toString()
            if (resendStr.contains("Re")) {
                loginViewModel.getOtp(loginViewModel.phone)
            }
        }

        // 点击展示键盘
        binding.code1.setOnClickListener {
            binding.keyboard.visibility = View.VISIBLE
        }
        binding.code2.setOnClickListener {
            binding.keyboard.visibility = View.VISIBLE
        }
        binding.code3.setOnClickListener {
            binding.keyboard.visibility = View.VISIBLE
        }
        binding.code4.setOnClickListener {
            binding.keyboard.visibility = View.VISIBLE
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineCameroonDialog().showNow(supportFragmentManager, "hotline")
            hitPointCameroon("SHOW_HOTLINE")
        }

        // 倒计时
        startCodeTimer()
    }

    @SuppressLint("SetTextI18n")
    fun startCodeTimer() {
        // 当前秒数
        var curTick = 120

        timer.cancel()
        timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                runOnUiThread {
                    binding.resend.isEnabled = false
                    binding.resend.text = "(${curTick}s)"
                    curTick -= 1
                    if (curTick == 0) {
                        timer.cancel()
                        binding.resend.text = "(Renvoyer)"
                        binding.resend.isEnabled = true
                    }
                }
            }
        }, 1000, 1000)
    }

    fun showMessage(message: String) {
        Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
    }

    private fun startNextActivity(
        activity: Class<out AppCompatActivity>? = null,
        params: HashMap<String, String> = HashMap()
    ) {
        val nextActivity = activity ?: return
        try {
            val intent = Intent(this, nextActivity)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
            params.keys.forEach { gKey ->
                intent.putExtra(gKey, params[gKey])
            }
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
        hitPointCameroon(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPointCameroon(type = this::class.java.simpleName, isPageEnd = true)
    }
}